//
//  MujiAudioComposition.m
//  testdemo
//
//  Created by yule on 2017/6/8.
//  Copyright © 2017年 yule. All rights reserved.
//

#import "MujiAudioComposition.h"
#import <AVFoundation/AVFoundation.h>
#import "MujiDubDialogLinesModel.h"

@implementation MujiAudioComposition

+ (void) sourceURLs:(NSArray *) sourceURLs dialogs:(NSArray *) dialogs composeToURL:(NSURL *) toURL completed:(void (^)(NSError *error)) completed
{

    //  合并所有的录音文件
    AVMutableComposition* mixComposition = [AVMutableComposition composition];
    
    //  音频插入的开始时间
    CMTime beginTime = kCMTimeZero;
    //  获取音频合并音轨
    AVMutableCompositionTrack *compositionAudioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
    
    //  用于记录错误的对象
    NSError *error = nil;
    
    for (int i = 0; i< sourceURLs.count; i++) {
    
        NSURL *sourceURL = [sourceURLs objectAtIndex:i];

        //      音频文件资源
        AVURLAsset  *audioAsset = [[AVURLAsset alloc]initWithURL:sourceURL options:nil];
        //      需要合并的音频文件的区间
        CMTimeRange audio_timeRange = CMTimeRangeMake(kCMTimeZero, audioAsset.duration);
        
        
        MujiDubDialogLinesModel *model = [dialogs objectAtIndex:i];
        Float64 cueEnd                   = 0;
        cueEnd   = 0.001 * [model.cueEnd intValue];

        Float64 cueStart                   = 0 ;
        cueStart   = 0.001 * [model.cueStart intValue];

        if (i != 0) {
            MujiDubDialogLinesModel *frontModel = [dialogs objectAtIndex:i - 1];

            Float64 frontcueEnd                   = 0 ;
            frontcueEnd   = 0.001 * [frontModel.cueEnd intValue];
            
            float temp = cueStart - frontcueEnd;
            NSLog(@"%f", temp);
            
            if (temp > 0) {
                beginTime = CMTimeAdd(beginTime, CMTimeMake(44100 *(cueStart - frontcueEnd), 44100));
            }
        }

        //      参数说明:
        //      insertTimeRange:源录音文件的的区间
        //      ofTrack:插入音频的内容
        //      atTime:源音频插入到目标文件开始时间
        //      error: 插入失败记录错误
        //      返回:YES表示插入成功,`NO`表示插入失败
        BOOL success = [compositionAudioTrack insertTimeRange:audio_timeRange ofTrack:[[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:beginTime error:&error];
        //      如果插入失败,打印插入失败信息
        if (!success) {
            NSLog(@"插入音频失败: %@",error);
        }
        //      记录开始时间
        beginTime = CMTimeAdd(beginTime, audioAsset.duration);
    }
    NSFileManager *manager = [NSFileManager defaultManager];
    
    BOOL isDir;
    NSLog(@"  %d    %d ",[manager fileExistsAtPath:[toURL path]], [manager fileExistsAtPath:[toURL path] isDirectory:&isDir]);
    NSLog(@"%d", isDir);
    
    if ([manager fileExistsAtPath:[toURL path]]) {
        
        NSLog(@" remove ");
        [manager removeItemAtPath:[toURL path] error:nil];
    }
    
    // 创建一个导入M4A格式的音频的导出对象
    AVAssetExportSession* assetExport = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetAppleM4A];
    //  导入音视频的URL
    assetExport.outputURL = toURL;
    //  导出音视频的文件格式
    assetExport.outputFileType = @"com.apple.m4a-audio";
    //  导入出
    [assetExport exportAsynchronouslyWithCompletionHandler:^{
        //      分发到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            completed(assetExport.error);
        });
    }];
}


@end
